import Flutter
import UIKit
import Photos

// 确保遵循 FlutterPlugin 协议
@objc class VideoSaver: NSObject, FlutterPlugin {
    // 实现 FlutterPlugin 的 register 方法
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "com.example.app/photos", binaryMessenger: registrar.messenger())
        let instance = VideoSaver()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }

    // 处理 Flutter 端的方法调用
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "saveVideoToAlbum":
            guard let args = call.arguments as? [String: String],
                  let path = args["path"],
                  let videoURL = URL(string: "file://\(path)") else {
                result(FlutterError(code: "INVALID_ARGUMENT", message: "Invalid path", details: nil))
                return
            }
            saveVideoToAlbum(videoURL: videoURL, result: result)
        default:
            result(FlutterMethodNotImplemented)
        }
    }

    // 保存视频到相册的私有方法
    private func saveVideoToAlbum(videoURL: URL, result: @escaping FlutterResult) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
        }) { success, error in
            if success {
                result(true)
            } else {
                result(FlutterError(code: "SAVE_FAILED",
                                  message: error?.localizedDescription ?? "保存失败",
                                  details: nil))
            }
        }
    }
}